import http from 'wechat-http'

// 接口基础地址
http.baseURL = 'https://live-api.itheima.net'

// 请求拦截器
http.intercept.request = (options) => {
  const defaultHeader = {}
  defaultHeader.Authorization = `Bearer ` + getApp().token
  options.header = Object.assign({}, defaultHeader, options.header)
  return options
}

// 响应拦截器
http.intercept.response = async (result) => {
  // console.log(res)
  //res.statusCode 响应状态码
  // 10000 业务正确
  const { code, message, data } = result.data
  if (code === 10000) {
    return data
  } else {
    if (code === 401) {
      const app = getApp()
      wx.request({
        url: http.baseURL + '/refreshToken',
        method: 'post',
        header: { Authorization: `Bearer ` + app.refreshToken },
        success: (res) => {
          if (res.data.code === 401) {
            app.setToken('token', '')
            app.setToken('refreshToken', '')
            const curPages = getCurrentPages()
            const page = curPages.pop()
            return wx.wx.redirectTo({
              url: '/pages/login/index?redirectUrl=' + page.route,
            })
          }
          if (res.data.code === 10000) {
            app.setToken('token', res.data.data.token)
            app.setToken('refreshToken', res.data.data.refreshToken)
            const config = Object.assign(result.config, {
              header: { Authorization: `Bearer ` + res.data.data.token },
            })
            return http(config)
          }
        },
      })
    }
  }
  //业务错误
  wx.utils.toast(message || '加载出错')
  return Promise.reject(message || '加载出错')
}

// 挂载到 wx 全局命名空间
wx.http = http

// 也可作为模块导出
export default http
